<script setup lang="ts">
import type { PropType } from "vue";
import type { Message } from "@/utils/database";
const props = defineProps({
  messages: {
    type: Array as PropType<Message[]>,
    default: () => [],
  },
  isOwnMsg: {
    type: Function as PropType<(msg: Message) => boolean>,
    required: true,
  },
  shouldShowTime: {
    type: Function as PropType<
      (currentMsg: Message, previousMsg: Message) => boolean
    >,
    required: true,
  },
});
</script>

<template>
  <div
    class="message-item"
    v-for="(item, index) in messages"
    :class="{
      'message-left': isOwnMsg(item),
      'message-right': !isOwnMsg(item),
    }"
  >
    <!-- 时间显示 -->
    <div class="message-time" v-if="shouldShowTime(item, messages[index - 1])">
      {{ item.timestamp }}
    </div>
    <!-- 消息内容 -->
    <div class="message-content">
      <!-- 左侧消息：左头像右气泡 -->
      <div class="avatar" v-if="isOwnMsg(item)">
        <el-avatar
          shape="square"
          :size="40"
          :src="''"
        />
      </div>
      <div class="message-bubble">{{ item.content }}</div>
      <!-- 右侧消息：左气泡右头像 -->
      <div class="avatar" v-if="!isOwnMsg(item)">
        <el-avatar
          shape="square"
          :size="40"
          :src="''"
        />
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.message-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 4px 0;
  width: 100%;
  min-width: 0;

  .message-time {
    width: 100%;
    font-size: 12px;
    color: #999;
    margin-bottom: 4px;
    text-align: center;
  }

  .message-content {
    display: flex;
    align-items: flex-start;
    width: 100%;
  }

  /* 把类名移到 message-item 上 */
  &.message-left {
    .message-content {
      justify-content: flex-start;
    }

    .avatar {
      margin-right: 10px;
      flex-shrink: 0;
    }

    .message-bubble {
      background: #ffffff;
      border: 1px solid #e5e5e5;
      border-radius: 4px 16px 16px 4px;
      max-width: 40%;
      text-align: left;
      padding: 8px 12px;
      box-shadow: 0 1px 1px rgba(124, 123, 123, 0.1);
      white-space: pre-wrap;
      word-wrap: break-word;
      word-break: break-word;
      overflow-wrap: break-word;
    }
  }

  &.message-right {
    .message-content {
      justify-content: flex-end;
    }

    .avatar {
      margin-left: 10px;
      flex-shrink: 0;
      order: 2;
    }

    .message-bubble {
      background: #95ec69;
      border: 1px solid #70d43d;
      border-radius: 16px 4px 4px 16px;
      max-width: 40%;
      text-align: left;
      padding: 8px 12px;
      box-shadow: 0 1px 1px rgba(124, 123, 123, 0.1);
      white-space: pre-wrap;
      word-wrap: break-word;
      word-break: break-word;
      overflow-wrap: break-word;
      order: 1;
    }
  }

  .message-bubble {
    line-height: 1.4;
    font-size: 14px;
    overflow-wrap: break-word;
    word-break: break-word;
    overflow: hidden;
  }
}
</style>
